/**
 * @Author: DengLibin
 * @Date: Create in 2022-12-01 09:27:38
 * @Description: http客户端
 */
package util

import (
	"bufio"
	"io"
	"net/http"
	"net/url"
	"os"
	"path"
	"time"

	"denglibin.io/common/log"
	"github.com/sirupsen/logrus"
)

var client *http.Client

func initClient() {
	if client == nil {
		client = http.DefaultClient
		client.Timeout = time.Second * 60 //设置超时时间
	}
}

/**
 * @Author: DengLibin
 * @Date: Create in 2022-12-01 09:28:25
 * @Description: 下载文件
 */
func DownFile(durl, filepath string) error {
	initClient()
	log.InitLog()
	uri, err := url.ParseRequestURI(durl)
	if err != nil {
		return err
	}
	filename := path.Base(uri.Path)
	logrus.Info("下载文件:", filename)

	resp, err := client.Get(durl)
	if err != nil {
		return err
	}
	body := resp.Body
	defer body.Close()

	reader := bufio.NewReaderSize(body, 1024*32)

	file, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer file.Close()
	writer := bufio.NewWriter(file)

	buff := make([]byte, 32*1024)
	written := 0

	for {
		nr, err := reader.Read(buff)
		if err != nil {
			//读取完毕
			if err == io.EOF {
				break
			}
			return err
		}
		if nr > 0 {
			nw, ew := writer.Write(buff[0:nr])

			if ew != nil {
				return ew
			}
			if nw > 0 {
				written += nw
			}

			if nr != nw {
				err = io.ErrShortWrite
				return err
			}
		}
	}
	return nil
}
